<template>
    <div class="div-view-search">
        <el-row gutter="20" class="search">
            <el-col id="btn0" :span="2">
                <el-button type="danger" @click="handleRejectBatch">批量删除</el-button>
            </el-col>
            <el-col id="btn1" :span="2">
                <el-button type="success" @click="handleApproveBatch">批量通过</el-button>
            </el-col>
            <el-col :offset="14" :span="4">
                <el-input v-model="searchName" placeholder="请输入服务名称" />
            </el-col>
            <el-col :span="2">
                <el-button type="primary" @click="handleSearch">查询</el-button>
            </el-col>
        </el-row>
    </div>
    <div class="div-view">
        <!-- 表格 -->
        <div class="table">
            <el-table :data="sortedAgencies" :header-cell-style="{ backgroundColor: '#f0f0f0' }" style="width: 100%"
                @sort-change="handleSortChange" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column property='serviceId' label="服务ID" />
                <el-table-column property="userId" label="发布用户ID" />
                <el-table-column property="serviceTitle" label="服务标题" />
                <el-table-column property="postTime" label="发布时间" sortable="custom" />
                <el-table-column property="postPosition" label="发布地点" />
                <el-table-column property="serviceStatus" label="状态" />
                <el-table-column property="favorNum" label="浏览数量" />
                <!-- 操作按钮 -->
                <el-table-column width="250" label="操作">
                    <template #default="{ row }">
                        <!-- 查看内容按钮，随时可点击 -->
                        <el-button type="info" link @click="viewServiceContent(row.serviceId)">
                            查看服务内容
                        </el-button>
                        <!-- 删除按钮，仅当状态为“上架”时可点击 -->
                        <el-button type="danger" @click="handleRejectApplication(row)"
                            :disabled="row.serviceStatus !== '审核中'" link>
                            删除
                        </el-button>
                        <!-- 通过审核按钮，仅当状态为“审核中”时可点击 -->
                        <el-button type="success" @click="handleApproveApplication(row)"
                            :disabled="row.serviceStatus !== '审核中'" link>
                            通过
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <div class="demo-pagination-block">
            <el-pagination v-model:currentPage="pageNum" v-model:pageSize="pageSize" :page-sizes="[5, 10, 15, 20]"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                style="display: flex; justify-content: flex-end; margin-top: 10px;" />
        </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" title="服务详情" width="500">
        <el-form :model="serviceDetails" label-width="120px">
            <el-form-item label="服务标题：">
                <span>{{ serviceDetails.serviceTitle }}</span>
            </el-form-item>
            <el-form-item label="服务内容：">
                <span>{{ serviceDetails.serviceContent }}</span>
            </el-form-item>
            <el-form-item label="发布时间：">
                <span>{{ serviceDetails.postTime }}</span>
            </el-form-item>
            <el-form-item label="图片：">
                <img :src="serviceDetails.imageUrl" alt="服务图片" style="max-width: 100%">
            </el-form-item>
            <el-form-item label="价格：">
                <span>{{ serviceDetails.servicePrice }}</span>
            </el-form-item>
            <el-form-item label="地点：">
                <span>{{ serviceDetails.postPosition }}</span>
            </el-form-item>
        </el-form>
        <div style="display: flex; justify-content: flex-end;">
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false" type="danger">关闭</el-button>
            </span>
        </div>
    </el-dialog>

</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

interface Service {
    serviceTitle: string;
    postTime: string;
    imageUrl: string;
    servicePrice: number;
    postPosition: string;
    serviceContent: string;
}


const serviceDetails = ref<Service>({} as Service);
const dialogVisible = ref(false);

const viewServiceContent = async (serviceId: number) => {
    try {
        // 注意这里的URL，我们将serviceId作为查询参数传递
        const response = await axios.get(`http://localhost:8088/services/check?serviceId=${serviceId}`);
        serviceDetails.value = response.data;
        dialogVisible.value = true;
    } catch (error) {
        console.error('获取服务内容失败:', error);
        ElMessage.error('获取服务内容失败');
    }
};
// 定义分页数据
const pageNum = ref(1);
const pageSize = ref(5);
// 定义总数据量
const total = ref(0);
const searchName = ref('');
//定义数据数组
const tableData = ref([]);
//定义选中的行
const selectedRows = ref([]);
const getData = async () => {
    try {
        const response = await axios.get('http://localhost:8088/services/getByPage', {
            params: {
                pageNum: pageNum.value,
                pageSize: pageSize.value,
            },
        });
        tableData.value = response.data.records;
        total.value = response.data.total;
        pageNum.value = response.data.current;
        pageSize.value = response.data.size;
    } catch (error) {
        console.error('跳转失败:', error);
    }
};
// 当前页或每页数量改变时重新获取数据
const handleSizeChange = () => {
    getData();
};
const handleCurrentChange = () => {
    getData();
};

// 处理选择变化
const handleSelectionChange = (val) => {
    selectedRows.value = val;
    console.log(selectedRows.value);
}

const handleSearch = async () => {
    try {
        const response = await axios.get('http://localhost:8088/services/getByName', 
        { params: { serviceTitle: searchName.value } });
        tableData.value = response.data;
    } catch (error) {
        console.error('查找出错:', error);
    }
};

// 更新操作的函数
const updateServiceStatus = async (serviceId, serviceStatus) => {
    try {
        // 构建包含ID和新状态的请求体
        const requestBody = {
            serviceId,
            serviceStatus,
        };

        const response = await axios.put(
            "http://localhost:8088/services/update",
            requestBody
        );

        if (response.data) {
            ElMessage.success("操作成功");// 操作成功，给用户反馈
            // 同步更新表格中的数据状态
            const service = tableData.value.find((item) => item.serviceId === serviceId);
            if (service) {
                service.serviceStatus = serviceStatus;
            }
        }
        return response.data;
    } catch (error) {
        console.error("更新失败:", error);
        ElMessage.error("更新失败");// 更新失败，给用户反馈
        return null;
    }
};

// 删除
const handleRejectApplication = (row) => {
    updateServiceStatus(row.serviceId, '下架'); 
};

// 通过审核
const handleApproveApplication = (row) => {
    updateServiceStatus(row.serviceId, '上架'); 
};

const handleRejectBatch = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning("请选择要删除的帖子");
        return;
    }
    try {
        const RequestBody = selectedRows.value.map((row) => ({
            serviceId: row.serviceId,
            serviceStatus: '下架',  // 固定为下架，或者根据需要动态赋值
        }));
        const response = await axios.put(
            "http://localhost:8088/services/updateByBatch",
            RequestBody
        );
        if (response.data) {
            ElMessage.success("操作成功"); // 操作成功，给用户反馈
            // 同步更新表格中的数据状态
            getData();
        }
        else {
            ElMessage.error("操作失败"); // 操作失败，给用户反馈
        }
    }catch (error) {
        console.error("更新失败:", error);
        ElMessage.error("更新失败"); // 更新失败，给用户反馈
    }
};

const handleApproveBatch = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning("请选择要通过的帖子");
        return;
    }
    try {
        const RequestBody = selectedRows.value.map((row) => ({
            serviceId: row.serviceId,
            serviceStatus: '上架',  
        }));
        const response = await axios.put(
            "http://localhost:8088/services/updateByBatch",
            RequestBody
        );
        if (response.data) {
            ElMessage.success("操作成功"); // 操作成功，给用户反馈
            getData();
        }
    }catch (error) {
        console.error("更新失败:", error);
        ElMessage.error("更新失败"); // 更新失败，给用户反馈
    }
};

// 组件挂载后获取初始数据
onMounted(() => {
    getData();
});


// 当前排序的属性和顺序
const sortProp = ref('');
const sortOrder = ref(''); // 'ascending' 或 'descending'
const sortedAgencies = computed(() => {
    return tableData.value.slice().sort((a, b) => {
        if (sortProp.value === 'postTime') {
            const timeA = new Date(a.postTime).getTime();
            const timeB = new Date(b.postTime).getTime();
            return sortOrder.value === 'ascending' ? timeA - timeB : timeB - timeA;
        }
        return 0;
    });
});

// 处理排序变化的函数
const handleSortChange = (newSortInfo) => {
    sortProp.value = newSortInfo.prop;
    sortOrder.value = newSortInfo.order;
};

const handleEdit = (row) => {
    // 编辑操作的逻辑
    console.log('Editing row:', row);
};
const handleDelete = (row) => {
    // 删除操作的逻辑
    console.log('Deleting row:', row);
};
</script>

<style scoped>
.el-header {
    padding-left: 0px;
    padding-right: 0px;
}

.el-main {
    background-color: #F2F2F2;
}

.el-aside {
    background-color: #7162A7;
    width: auto;
}

.div-view {
    background-color: #fff;
    padding: 10px 10px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    margin-bottom: 10px;
    /* 下边距 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影 */
}

.div-view-search {
    background-color: #fff;
    padding: 10px 10px;
    /* 内边距 */
    border-radius: 5px;
    /* 圆角 */
    margin-bottom: 10px;
    /* 下边距 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影 */
}



.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}
</style>